//
//  BHImagePicker.m
//  BHFoundation
//
//  Created by peironggao on 2018/4/27.
//

#import "BHImagePicker.h"
#import <UIKit/UIKit.h>
#import <AssetsLibrary/AssetsLibrary.h>

@interface BHImagePicker()<UINavigationControllerDelegate, UIImagePickerControllerDelegate>

@property (nonatomic, copy) void(^imagePickComplete)(BHImagePickerState status, UIImage *image);

@end

@implementation BHImagePicker

+ (instancetype)shareInstance
{
    static dispatch_once_t onceToken;
    static BHImagePicker *instance = nil;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
    });
    return instance;
}

- (void)pickImageSourceType:(UIImagePickerControllerSourceType)type
                  allowEdit:(BOOL)allowEdit
                   complete:(void(^)(BHImagePickerState status, UIImage *image))complete{
    //判断是否已授权
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {
        ALAuthorizationStatus authStatus = [ALAssetsLibrary authorizationStatus];
        if (authStatus == ALAuthorizationStatusDenied)
        {
            if (complete)
            {
                complete(BHImagePickerUnauthed, nil);
            }
            return;
        }
        
    }
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.allowsEditing = allowEdit;
        picker.sourceType = type;
        [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:picker animated:YES completion:nil];
        self.imagePickComplete = complete;
    } else {
        if (complete)
        {
            complete(BHImagePickerUnavaiable, nil);
        }
    }
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
    if (self.imagePickComplete)
    {
        self.imagePickComplete(BHImagePickerCancel, nil);
    }
    self.imagePickComplete = nil;
}

- (void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    UIImage *theImage = nil;
    if ([picker allowsEditing]){
        theImage = [info objectForKey:UIImagePickerControllerEditedImage];
    } else {
        theImage = [info objectForKey:UIImagePickerControllerOriginalImage];
    }
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    if (self.imagePickComplete)
    {
        self.imagePickComplete(BHImagePickerSuccess, theImage);
    }
    self.imagePickComplete = nil;

}

@end
